package com.suse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suse.dto.EmployeeDto;
import com.suse.pojo.Employee;
import com.suse.service.EmployeeService;
import com.suse.util.ResultVo;
import com.suse.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Resource
    private EmployeeDao employeeDao;

    //获取邮件发送服务类
    @Autowired
    JavaMailSender javaMailSender;

    @Value("${file.address}")
    String fileAddress;


    @Override
    public ResultVo update(Employee u, HttpServletRequest request) {
        try {
            int num;
            String employeeName = (String) request.getSession().getAttribute("name");
            if (u.getEmployeeId() == null) {
                QueryWrapper<Employee> uu = new QueryWrapper<>();
                uu.eq("employee_name", employeeName);
                Employee employee = employeeDao.selectOne(uu);
                if (employee != null) {
                    employee.setEmployeePassword(u.getEmployeePassword());
                    System.out.println("即将更新的对象: " + employee);
                    num = employeeDao.updateById(employee);
                } else {
                    return ResultVo.error("员工信息不存在");
                }
            }else{
                num = employeeDao.updateById(u);
            }
            System.out.println("num结果: " + num);
            if (num > 0)
            {return ResultVo.success("修改成功");}
            else
            {return ResultVo.error("修改失败");}
        }catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("数据不对");
        }
    }

    //删除
    @Override
    public ResultVo delete(Integer id) {
        try {
            int num = employeeDao.deleteById(id);
            if (num > 0) {return ResultVo.success("删除成功");}
            else{return ResultVo.error("删除失败");}
        }catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("数据异常");
        }
    }

    @Override
    public ResultVo search(EmployeeDto dto){
        try{
            //这里我使用的employee_name 和role来查询
            QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
            if (dto.getEmployeeName() != null && !dto.getEmployeeName().isEmpty())
            {queryWrapper.like("employee_name", dto.getEmployeeName());}
            if (dto.getEmployeeGender() != null && !dto.getEmployeeGender().isEmpty())
            {queryWrapper.eq("employee_gender", dto.getEmployeeGender());}

            Page<Employee> page = new Page<>(dto.getPage(), dto.getRow());
            Page<Employee> infoPage = employeeDao.selectPage(page,queryWrapper);
            if(!infoPage.getRecords().isEmpty()){
                HashMap<String,Object> map = new HashMap<>();
                map.put("list",infoPage.getRecords());
                map.put("total",infoPage.getTotal());
                return ResultVo.success("成功",map);
            }else{
                return ResultVo.error("没有数据");
            }
        }catch(Exception e){
            e.printStackTrace();
            return ResultVo.error("数据异常");
        }
    }
    //新增
    @Override
    public ResultVo add(Employee u) {
        //查询用户名是否存在，要求姓名唯一
        QueryWrapper<Employee> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("employee_name",u.getEmployeeName());
        Employee employee=employeeDao.selectOne(queryWrapper);
        if(employee!=null){
            return ResultVo.error("用户名已存在");
        }
        // 设置默认密码
        u.setEmployeePassword("password0");
        // 设置默认头像
        u.setSrc("/upload/2025-01-10/2cbb7777-c4a4-47d6-ad82-1f7c507ab93a.jpg");
        try {
            int num = employeeDao.insert(u);
            if (num > 0) {return ResultVo.success("新增成功");}
            else {return ResultVo.error("新增失败");}
        }catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("数据异常");
        }
    }
    //发送验证码
    @Override
    public ResultVo sendCode(String email, HttpServletRequest request) {
        try {
            //创建一个普通邮件对象
            SimpleMailMessage message=new SimpleMailMessage();
            //定义发件人
            message.setFrom("3169819882@qq.com");
            //定义收件人
            message.setTo(email);
            //定义邮件标题
            message.setSubject("验证码");
            //随机的四位数验证码
            int code = new Random().nextInt(9000) + 1000;
            //定义正文
            message.setText("您的验证码为："+code);
            //发送邮件
            javaMailSender.send(message);
            //把验证码存入session中
            request.getSession().setAttribute("code",code);
            return ResultVo.success("验证码发送成功");
        } catch (MailException e) {
            e.printStackTrace();
            return ResultVo.error("验证码发送失败");
        }
    }
    //验证验证码
    @Override
    public ResultVo verify(String code, HttpServletRequest request) {
        //从session中获取验证码
        String captcha= request.getSession().getAttribute("code")+"";
        //判断验证码是否正确
        if(captcha.equals(code)){
            //验证码正确，登录成功
            return ResultVo.success("验证码正确");
        }
        return ResultVo.error("验证码错误");

    }


    @Override
    public ResultVo fileUpload(MultipartFile file, HttpServletRequest request) {
        try {
            // 获取文件名和文件扩展名
            String fullname = file.getOriginalFilename();
            String fileExtension = fullname.substring(fullname.lastIndexOf(".") + 1); // 获取扩展名
            String uuid = UUID.randomUUID().toString();
            String newFileName = uuid + "." + fileExtension;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String newDir = format.format(new Date());
            File dir = new File(fileAddress + "/" + newDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File destFile = new File(dir, newFileName);
            file.transferTo(destFile); // 将文件保存到目标路径

            // 获取文件的相对路径（用于保存到数据库）
            String fileSrc = "/upload/" + newDir + "/" + newFileName;

            // 判断文件类型，分别处理图片和视频
            Map<String, Object> map = new HashMap<>();
            if ("mp4".equalsIgnoreCase(fileExtension)) {
                map.put("type", "video");
                map.put("src", fileSrc);
            } else {
                map.put("type", "image");
                map.put("src", fileSrc);
            }
            String EmployeeName = request.getSession().getAttribute("name")+"";
            QueryWrapper<Employee> u = new QueryWrapper<>();
            u.eq("employee_name",EmployeeName);
            Employee employee = new Employee();
            employee.setSrc(fileSrc);
            employeeDao.update(employee,u);
            return ResultVo.success("success",map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("文件上传失败");
        }
    }

    //登录
    @Override
    public ResultVo login(Employee u,HttpServletRequest request) {
        //登录查询，查询用户名是否存在
        QueryWrapper<Employee> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("employee_name",u.getEmployeeName());
        Employee employee=employeeDao.selectOne(queryWrapper);
        if(employee==null){
            return ResultVo.error("用户名错误");
        }
        //密码验证
        if(employee.getEmployeePassword().equals(u.getEmployeePassword())){
            //登录成功，记录登录状态
            request.getSession().setAttribute("name",employee.getEmployeeName());
            HashMap<Object, Object> map=new HashMap<>();
            map.put("src",employee.getSrc());
            map.put("role",employee.getEmployeeRole());
            return ResultVo.success("登录成功",map);
        }
        return ResultVo.error("密码错误");
    }
}
